﻿using Microsoft.AspNetCore.Mvc;
using System;
using WxOpenPLatCore.Interfaces;
using WxOpenPLatCore.Models;
using WxOpenPLatCore.Services;
using WxOpenPlatLibCore.Utils;

namespace WxOpenPLatCore.Controllers
{
    public class DomainsController : Controller
    {
        private readonly DomainsService _service;
        public DomainsController(DomainsService service)
        {
            _service = (DomainsService)service;
        }

        public IActionResult query()
        {
            var list = _service.Query();
            return new JsonResult(new { sucess = true, info = "", data = list });
        }

        public IActionResult get()
        {
            Domains model = _service.GetById(DataConvert.ObjectToInt32(Request.Form["id"],0));
            return new JsonResult(new { sucess = true, info = "", data = model });
        }

        public IActionResult del()
        {
            bool ret = _service.Delete(Request.Form["del_id"]);
            return new JsonResult(new { sucess = ret, info = "" });
        }

        public IActionResult save()
        {
            Domains model = new Domains();
            System.Reflection.PropertyInfo[] info = typeof(Domains).GetProperties();
            System.Text.StringBuilder fields = new System.Text.StringBuilder();
            System.Text.StringBuilder values = new System.Text.StringBuilder();
            foreach (var property in info)
            {
                if (Request.Form.ContainsKey(property.Name))
                {
                    string value = Request.Form[property.Name];
                    if (value=="null")
                    {
                        continue;
                    }
                    if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(System.Nullable<>)))
                    {
                        System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(property.PropertyType);
                        property.SetValue(model, Convert.ChangeType(value, nullableConverter.UnderlyingType), null);
                    }
                    else
                    {
                        property.SetValue(model, Convert.ChangeType(value, property.PropertyType), null);
                    }
                }
            }
            bool ret = _service.AddOrUpdate(model);
            return new JsonResult(new { sucess = ret, info = "" });
        }
    }
}